package com.sophialex.health.record.views.account;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.ISharedImages;

import com.sophialex.health.common.platform.SuperContext;
import com.sophialex.health.person.vo.HrPerson;
import com.sophialex.health.person.vo.SoapService;
import com.sophialex.health.record.Activator;
import com.sophialex.health.record.Messages;
import com.sophialex.health.record.common.Constants;
import com.sophialex.health.record.common.SOAPServiceDispath;
import com.sophialex.health.record.common.util.DataSource;
import com.sophialex.health.record.common.util.EventType;
import com.sophialex.health.record.common.util.HealthRecordListenerRegister;
import com.sophialex.health.record.common.utils.CommonUtils;
import com.sophialex.health.record.ui.account.PersonAccountComposite;
import com.sophialex.health.record.ui.account.PersonAccountUI;
import com.sophialex.health.record.views.query.HrPersonQueryView;
import com.sophialex.health.system.frame.background.BackManager;
import com.sophialex.health.system.frame.background.task.TaskAdapter;
import com.sophialex.health.system.frame.dialog.DialogManager;
import com.sophialex.health.system.frame.resource.RcpResourceManager;
import com.sophialex.health.system.frame.util.ViewUitl;

public class PersonAccountView extends PersonAccountUI {
	public PersonAccountView() {
	}

	private PersonAccountComposite accountCom;

	private Composite parent;

	public final static String ID = "com.sophialex.health.record.views.account.PersonAccountView";

	private List<SoapService> soapServiceList;

	private TreeViewer viewer;

	protected void doReturn() {
		HrPersonQueryView v = ViewUitl.showView(HrPersonQueryView.class);
		// ViewUitl.hideView(PersonAccountView.ID);     //暂时这样处理 先注释        broswer会导致虚拟机直接退出

	}

	protected void doPrint() {
		boolean result = browser.execute("printAccount();");
		if(!result) {
			DialogManager.invokeWarnDlg(Messages.getString("Print.0"));
		}

	}

	public void createPartControl(Composite parent) {
		this.parent = parent;
		super.createPartControl(parent);
	}

	@Override
	protected void buidServiceControl(Composite com) {
		com.setLayout(new FillLayout());
		buildPersonAccountComposite(com);

	}

	private void buildPersonAccountComposite(Composite com) {
		accountCom = new PersonAccountComposite(com, SWT.NONE, viewer);
		viewer = accountCom.getReturnView();
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		viewer.expandToLevel(2);
		viewer.addSelectionChangedListener(new ISelectionChangedListener() {
			public void selectionChanged(SelectionChangedEvent event) {
				if(event.getSelection().isEmpty()) {
					return;
				}
				if(event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event.getSelection();
					for(Iterator iterator = selection.iterator(); iterator.hasNext();) {
						Object element = iterator.next();
						if(element instanceof TreeObject) {
							TreeObject treeObject = (TreeObject) element;
							String url = SOAPServiceDispath.serviceMapAccount.get(treeObject.getBusType());
							if(StringUtils.isNotBlank(url)) {
								final String toUrl = url + +SuperContext.currentPerson.getId();
								// BusyIndicator.showWhile(Display.getDefault(),
								// new Runnable() {
								// public void run() {
								// browser.setUrl(toUrl);
								// }

								// });

								BackManager.getInstance().addTask(new TaskAdapter() {
									public void doTask() {
										browser.setUrl(toUrl);
									}
								}, true);
							} else {
								if(treeObject.getBusType().longValue() == 1) {
									SoapService soapService = treeObject.getSoapService();
									System.out.println(soapService.getId() + "  " + soapService.getBusType());
								}

							}
						}

					}

				}

			}
		});
		try {
			// accountCom.setData();
			// logCom.addMessageLisener();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	private void initData() {
		HrPerson currentPerson = SuperContext.currentPerson;
		if(currentPerson != null) {
			soapServiceList = DataSource.soapService.getSoapServiceByPerosnId(currentPerson.getId());
			accountCom.getNameLabel().setText(Messages.getString("PersonAccount.title") + currentPerson.getName());
		} else {
			soapServiceList = null;
		}

	}

	public class TreeObject implements IAdaptable {
		private String name;

		private SoapService soapService;

		private TreeParent parent;

		private Long busType;

		public Long getBusType() {
			return busType;
		}

		public void setBusType(Long busType) {
			this.busType = busType;
		}

		public TreeObject(String name) {
			this.name = name;
		}

		public String getName() {
			return name;
		}

		public SoapService getSoapService() {
			return soapService;
		}

		public void setSoapService(SoapService soapService) {
			this.soapService = soapService;
		}

		public void setParent(TreeParent parent) {
			this.parent = parent;
		}

		public TreeParent getParent() {
			return parent;
		}

		public String toString() {
			return getName();
		}

		public Object getAdapter(Class key) {
			return null;
		}
	}

	public class TreeParent extends TreeObject {
		private ArrayList children;

		public TreeParent(String name) {
			super(name);
			children = new ArrayList();
		}

		public void addChild(TreeObject child) {
			children.add(child);
			child.setParent(this);
		}

		public void removeChild(TreeObject child) {
			children.remove(child);
			child.setParent(null);
		}

		public TreeObject[] getChildren() {
			return (TreeObject[]) children.toArray(new TreeObject[children.size()]);
		}

		public boolean hasChildren() {
			return children.size() > 0;
		}
	}

	class ViewContentProvider implements IStructuredContentProvider, ITreeContentProvider {
		private TreeParent invisibleRoot;

		public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}

		public void dispose() {
		}

		public Object[] getElements(Object parent) {
			if(parent.equals(getViewSite())) {
				if(invisibleRoot == null)
					initialize();
				return getChildren(invisibleRoot);
			}
			return getChildren(parent);
		}

		public Object getParent(Object child) {
			if(child instanceof TreeObject) {
				return ((TreeObject) child).getParent();
			}
			return null;
		}

		public Object[] getChildren(Object parent) {
			if(parent instanceof TreeParent) {
				return ((TreeParent) parent).getChildren();
			}
			return new Object[0];
		}

		public boolean hasChildren(Object parent) {
			if(parent instanceof TreeParent)
				return ((TreeParent) parent).hasChildren();
			return false;
		}

		private void initDefault(TreeParent root) {
			TreeParent tparent1 = new TreeParent(Messages.getString("PersonItem.1"));
			tparent1.setBusType(Constants.GRJKDA_BUSSTYPE);
			root.addChild(tparent1);
			TreeObject tparent2 = new TreeObject(Messages.getString("PersonItem.2"));
			tparent2.setBusType(Constants.JKK);
			tparent1.addChild(tparent2);
			TreeObject tparent3 = new TreeObject(Messages.getString("PersonItem.3"));
			tparent3.setBusType(Constants.PERSONRECORD);
			tparent1.addChild(tparent3);
			TreeObject tparent4 = new TreeObject(Messages.getString("PersonItem.4"));
			tparent4.setBusType(Constants.ISSUE);
			tparent1.addChild(tparent4);
		}

		public void initialize() {
			initData();
			TreeParent root = new TreeParent(Messages.getString("PersonItem.0"));

			initDefault(root); // 默认的条目

			if(soapServiceList != null) {
				Map<Long, List<Long>> map = CommonUtils.getBusTypeGroup(CommonUtils.getBusTypes(soapServiceList));
				if(map != null && !map.isEmpty()) {
					int i = 1;
					for(Iterator it = map.keySet().iterator(); it.hasNext();) {
						Long sub = (Long) it.next();
						List<Long> list = map.get(sub);
						String big_title = CommonUtils.getBusTypeName(sub);
						TreeParent tparent = new TreeParent(big_title);
						root.addChild(tparent);

						if(list != null && list.size() > 0) {
							for(int j = 0; j < list.size(); j++) {
								Long sub2 = list.get(j);
								int k = 0;
								int count = 0;
								List<TreeObject> treeList = new ArrayList<TreeObject>();
								for(Iterator ite = soapServiceList.iterator(); ite.hasNext();) {
									SoapService service = (SoapService) ite.next();
									if(sub2.equals(service.getBusType())) {
										SOAPServiceDispath.serviceMap.get(service.getBusType());
										String serviceTime = DateUtil.formatDate(service.getServiceTime(), "yyyy-MM-dd");
										TreeObject t = new TreeObject(serviceTime);
										t.setSoapService(service);
										t.setBusType(1l);
										treeList.add(t);
										count++;
										k++;
									}
								}
								String serviceName = CommonUtils.getBusTypeName(sub2) + " （" + count + "）";
								TreeParent sparent = new TreeParent(serviceName);
								sparent.setBusType(0l);
								tparent.addChild(sparent);
								tparent.setBusType(sub);
								for(int l = 0; l < treeList.size(); l++) {
									sparent.addChild(treeList.get(l));
								}
							}
						}
						i++;
					}
				}
			}

			invisibleRoot = new TreeParent("");
			invisibleRoot.addChild(root);
		}
	}

	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}

		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if(obj instanceof TreeParent) {
				TreeParent o = (TreeParent) obj;
				if(o.getBusType() == null) {
					imageKey = "icons/view/addCate.png";
				} else if(o.getBusType().longValue() == 0) {
					imageKey = "icons/view/brzl.png";
				} else {
					imageKey = "icons/view/" + o.getBusType() + ".png";
				}
				return RcpResourceManager.getPluginImage(Activator.getDefault(), imageKey);
			}

			return RcpResourceManager.getPluginImage(Activator.getDefault(), "icons/view/yzxx.png");

		}
	}

	public void refresh() {
		if(parent != null && parent.isDisposed()) {
			parent.setVisible(true);
		}
		initData();
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(getViewSite());
		viewer.expandToLevel(2);
	}
}
